<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\BaseController;
use think\facade\Session;
use think\Request;
use app\common\model\User as UserModel;


class User extends BaseController
{
    //用户页面
    public function index(Request $request)
    {
        if (str_contains($request->url(), 'register')) {
            return view('/register');
        } else {
            return view('/login');
        }
    }

    //退出登录
    public function logout()
    {
        Session::set("user", null);
        $this->redirect('/index');
    }

    //登录
    public function login(Request $request) {
        try {
            $username = $request->post('username');
            $password = $request->post('password');

            $user = UserModel::where(['username' => strip_tags(trim($username))])->find();
            if (!$user) {
                $user = UserModel::where(['phone' => strip_tags(trim($username))])->find();
            }
            if (!$user) {
                throw new \Exception("用户不存在");
            }
            if (!password_verify($password, $user['password'])) {
                throw new \Exception("用户密码错误");
            }
            $user = $user->toArray();
            unset($user['password']);
            Session::set('user', $user);
            $this->success('登录成功');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    //注册
    public function register(Request $request) {
        try {
            $data = $request->post();
            $username = $data['username'];
            $password = $data['password'];
            $where['username'] = strip_tags(trim($username));
            $user = UserModel::where($where)->find();
            if ($user) {
                throw new \Exception("用户已存在");
            }
            $data['password'] = password($password);
            UserModel::create($data);
            $this->success('注册成功');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
